package leetcode.templates.presum;

import java.util.HashMap;
import java.util.Map;

public class MaxPreSums2 {

	// 二维前缀和1
	public int[][] presum(int[][] matrix) {
		int m = matrix.length, n = matrix[0].length;
		int[][] presums = new int[m + 1][n];
		for (int i = 1; i <= m; i++) {
			for (int j = 0; j < n; j++) {
				presums[i][j] = matrix[i - 1][j] + presums[i - 1][j];
			}
		}
		// do something
		int ans = 0;
		for (int l = 0; l < m; l++) {
			for (int r = l + 1; r <= m; r++) {
				int[] cur = new int[n];
				for (int k = 0; k < n; k++) {
					cur[k] = presums[r][k] - presums[l][k];
				}
				// ans += find(cur, target);
			}
		}
		return presums;
	}

	// 二维前缀和2
	public int numSubmatrixSumTarget(int[][] matrix, int target) {
		int m = matrix.length, n = matrix[0].length;
		int ans = 0;
		for (int l = 0; l < m; l++) {
			int[] cur = new int[n];
			for (int r = l; r < m; r++) {
				for (int k = 0; k < n; k++) {
					cur[k] = cur[k] + matrix[r][k];
				}
				// do something
				ans += find(cur, target);
			}
		}
		return ans;
	}

	private int find(int[] nums, int target) {
		int ans = 0;
		Map<Integer, Integer> hash = new HashMap<>();
		hash.put(0, 1);
		int sum = 0;
		for (int num : nums) {
			sum += num;
			ans += hash.getOrDefault(sum - target, 0);
			hash.put(sum, hash.getOrDefault(sum, 0) + 1);
		}
		return ans;
	}

}
